package com.gzw.jackyweather;


import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gzw.jackyweather.db.City;
import com.gzw.jackyweather.db.CityManger;
import com.gzw.jackyweather.db.CityWeatherInfo;
import com.gzw.jackyweather.db.Skin;
import com.gzw.jackyweather.gson.Weather;
import com.gzw.jackyweather.service.AutoUpdateService;
import com.gzw.jackyweather.util.HttpUtil;
import com.gzw.jackyweather.util.Utility;
import com.gzw.jackyweather.weight.AutoDrawLayout;
import com.zhy.autolayout.utils.AutoUtils;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CitySettingActivity extends BaseActivity {

    private AutoDrawLayout drawLayout;
    private GridView gv;
    private Button btn_back;
    private ProgressDialog progressDialog;
    private ImageView iv_backGroud;
    private GridViewAdapter adapter;
    private List<CityManger> cityMangers = new ArrayList<>();

    @Override
    public int getContentViewID() {
        return R.layout.activity_city_setting;
    }

    @Override
    protected void initView() {

        cityMangers.addAll(DataSupport.findAll(CityManger.class));
        cityMangers.add(new CityManger());

        drawLayout = (AutoDrawLayout) findViewById(R.id.dl);
        iv_backGroud = (ImageView) findViewById(R.id.iv_background);

        List<Skin> skins = DataSupport.where("isDefault = ?", "1").find(Skin.class);
        if (skins.size() != 0) {
            if (skins.get(0).getImgId() == 0) {
                Glide.with(CitySettingActivity.this).load(skins.get(0).getFlag()).into(iv_backGroud);
            } else {
                iv_backGroud.setImageResource(skins.get(0).getImgId());
            }
        }

        gv = (GridView) findViewById(R.id.gv);
        btn_back = (Button) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        adapter = new GridViewAdapter(cityMangers);
        gv.setAdapter(adapter);
    }

    public void requestWeather(final String weatherId) {

        showProressDialog();

        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
                "&key=" + Contans.KEY;

        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        if (weather != null && "ok".equals(weather.status)) {

                            List<CityWeatherInfo> infos = DataSupport.where("weather_id=?", weather.basic.weatherId).find(CityWeatherInfo.class);
                            //查询数据库中的数据，如果没有就添加，如果有就更新
                            if (infos.size() != 0) {
                                ContentValues values = new ContentValues();
                                values.put("weather_info", responseText);
                                DataSupport.updateAll(CityWeatherInfo.class, values, "weather_id = ?", weatherId);
                            } else {
                                CityWeatherInfo info = new CityWeatherInfo();
                                info.setWeather_id(weather.basic.weatherId);
                                info.setWeather_info(responseText);
                                info.save();
                            }

                            List<CityManger> cityMangers = DataSupport.where("weather_id = ?", weather.basic.weatherId).find(CityManger.class);
                            if (cityMangers.size() == 0) {
                                //说明没有数据，添加一条数据
                                CityManger manger = new CityManger();
                                manger.setDefault(false);
                                manger.setWeather_id(weather.basic.weatherId);
                                manger.setCityName(weather.basic.cityName);
                                manger.setDegree(weather.now.temperature + "℃");
                                manger.setWeather_info(weather.now.more.info);
                                manger.save();

                            } else {
                                //有数据，更新一条数据
                                ContentValues values = new ContentValues();
                                values.put("degree", weather.now.temperature + "℃");
                                values.put("cityName", weather.basic.cityName);
                                values.put("weather_info", weather.now.more.info);
                                DataSupport.updateAll(CityManger.class, values, "weather_id = ?", weather.basic.weatherId);
                            }

//                            cityMangers.clear();
//                            cityMangers.addAll(DataSupport.findAll(CityManger.class));
//                            cityMangers.add(new CityManger());
//                            if (adapter != null) {
//                                adapter.notifyDataSetChanged();
//                            }

                            if (adapter != null) {
                                CityManger manger = new CityManger();
                                manger.setDefault(false);
                                manger.setWeather_id(weather.basic.weatherId);
                                manger.setCityName(weather.basic.cityName);
                                manger.setDegree(weather.now.temperature + "℃");
                                manger.setWeather_info(weather.now.more.info);
                                adapter.addItem(manger);
                            }

                            drawLayout.closeDrawer(GravityCompat.START);
                            //开启一个服务，每8小时更新一次天气数据

                        } else {
                            Toast.makeText(CitySettingActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(CitySettingActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        closeProgressDialog();
                    }
                });
            }
        });
    }

    public void setWeatherId(String weatherId) {
        requestWeather(weatherId);
    }

    /**
     * 显示进度对话框
     */
    private void showProressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("拼命加载中...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }


    class GridViewAdapter extends BaseAdapter {


        private List<CityManger> list;

        public GridViewAdapter(List<CityManger> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.city_item, parent, false);
                holder.tv_city = (TextView) convertView.findViewById(R.id.tv_city);
                holder.tv_degree = (TextView) convertView.findViewById(R.id.tv_degree);
                holder.tv_moren = (TextView) convertView.findViewById(R.id.tv_moren);
                holder.tv_weather_info = (TextView) convertView.findViewById(R.id.tv_weather_info);
                holder.btn_del = (Button) convertView.findViewById(R.id.btn_del);
                holder.btn_add = (Button) convertView.findViewById(R.id.btn_add);
                holder.ll = (LinearLayout) convertView.findViewById(R.id.ll);
                holder.ll1 = (LinearLayout) convertView.findViewById(R.id.ll1);
                convertView.setTag(holder);
                AutoUtils.auto(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_city.setText(list.get(position).getCityName());
            holder.tv_degree.setText(list.get(position).getDegree());
            holder.tv_weather_info.setText(list.get(position).getWeather_info());

            if (position == list.size() - 1) {
                holder.ll.setVisibility(View.GONE);
                holder.ll1.setVisibility(View.VISIBLE);

            } else {
                holder.ll.setVisibility(View.VISIBLE);
                holder.ll1.setVisibility(View.GONE);

            }

            holder.tv_moren.setText(list.get(position).isDefault() ? "默认" : "设置默认");

            holder.tv_moren.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setDefault(false);
                        ContentValues values = new ContentValues();
                        values.put("isDefault", 0);
                        DataSupport.updateAll(CityManger.class, values, "weather_id = ?", list.get(i).getWeather_id());
                    }
                    ContentValues values1 = new ContentValues();
                    values1.put("isDefault", 1);
                    DataSupport.updateAll(CityManger.class, values1, "weather_id = ?", list.get(position).getWeather_id());

                    list.get(position).setDefault(true);
                    notifyDataSetChanged();
                }
            });

            holder.btn_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeItem(position);
                }
            });

            holder.btn_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    addItem();
//                    Toast.makeText(CitySettingActivity.this, "弹出一个城市选择的fragment", Toast.LENGTH_SHORT).show();
                    showDialog();
                }
            });

            return convertView;
        }

        public void removeItem(int position) {
            int i = DataSupport.deleteAll(CityManger.class, "weather_id = ?", list.get(position).getWeather_id());
            list.remove(position);
            notifyDataSetChanged();
        }

        //增加一个城市
        public void addItem(CityManger cityManger) {

            list.add(list.size() - 1, cityManger);
            notifyDataSetChanged();
        }

        //显示DialogFragment,添加一个城市
        private void showDialog() {
            drawLayout.openDrawer(GravityCompat.START);
            setSystemUIState(true);
        }

    }

    class ViewHolder {
        TextView tv_city;
        TextView tv_weather_info;
        TextView tv_degree;
        TextView tv_moren;
        Button btn_del;
        Button btn_add;
        LinearLayout ll, ll1;
    }
}
